package com.example.demo810.vo;

import com.example.demo810.exception.BaseException;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * @author lzh
 * @date 2020/8/10 - 14:48
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class AjaxResponse<T> {
    /**
     * 错误码 0表示没有错误(异常) 其他数字代表具体错误码
     */
    private int code;
    /**
     * 后端返回消息
     */
    private String msg;
    /**
     * 后端返回的数据
     */
    private T data;

    public AjaxResponse(int code, String msg) {
        this.code = code;
        this.msg = msg;
    }

    public static <T> AjaxResponse<T> error(String message) {
        AjaxResponse<T> ajax = new AjaxResponse<T>();
        ajax.setCode(500);
        ajax.setMsg(message);
        return ajax;
    }


    public static <T> AjaxResponse<T> successMsg(String message) {
        AjaxResponse<T> ajax = new AjaxResponse<T>();
        ajax.setCode(0);
        ajax.setMsg(message);
        return ajax;
    }


    public static <T> AjaxResponse<T> successMsgData(String message, T data) {
        AjaxResponse<T> ajax = new AjaxResponse<T>();
        ajax.setCode(0);
        ajax.setMsg(message);
        ajax.setData(data);
        return ajax;
    }


    public AjaxResponse(Exception ex) {
        if (ex instanceof BaseException) {
            this.code = ((BaseException) ex).getCode();
            this.msg = ex.getMessage();
        }else if (ex instanceof org.springframework.web.servlet.NoHandlerFoundException){
            this.code = 404;
            this.msg = ex.getMessage();
        }
        else {
            this.code = 99999;// 其他未定义异常
            this.msg = ex.getMessage();
        }
    }
}
